<template>
  <div id="taskForm" class="templateBox">
    <!-- 一、申请企业基本情况 -->
    <a-spin :spinning="loading" size="large">
      <div id="tableForm" class="tableBox" :key="formKey">
        <!-- <a-button @click="changestyle">切换样式</a-button> -->
        <a-form-model
          ref="refForm_1"
          :rules="rules"
          :model="formData"
          v-if="loading == false && typeof formJson.list !== 'undefined' && typeof formJson.config !== 'undefined'"
          :layout="formJson.config.layout"
          :hideRequiredMark="formJson.config.hideRequiredMark"
          :style="formJson.config.customStyle"
        >
          <buildBlocks
            ref="formBuildRef"
            v-for="(record, index) in formJson.list"
            :record="record"
            :disabled="false"
            :formConfig="formJson.config"
            :key="index"
            :formJson="formJson"
            @updatedValueF="updatedValueS"
            @fHelp="sTriggerEvent"
            @rowDbclick="rowDbclick"
            @rowMouseOver="rowMouseOver"
            @resMouseleave="resMouseleave"
            @fSetFormData="sSetFormData"
            @fSetSonState="sSetSonState"
            @f_updateCheck="s_updateCheck"
            @f_btnClick="s_btnClick"
            :defaultHidden="defaultHidden"
            :pattern="pattern"
            :FactiveItem="activeItem"
            :activeList="activeList"
            :childrenFormData="childrenFormData"
            :formData="formData"
            :fieldMap="fieldMap"
            :nowStepid="nowStepid"
          />
        </a-form-model>
      </div>
    </a-spin>

    <!-- 编辑被申请人 -->
    <EditTargetName
      ref="editTargetNameRef"
      :applyid="$route.params.faapplyid || $route.params.applyid"
      :pattern="pattern"
      :needChangeTarget="true"
    />

    <!-- 常用语弹框 -->
    <Comword :applyid="$route.params.faapplyid || $route.params.applyid" ref="comwordRef" />

    <!-- 三级文书预览抽屉 -->
    <ApprovalDocPreview ref="approvalDocPreviewRef" />

    <!-- 干预行政复议弹框 -->
    <CaseDecisionIntervene ref="caseDecisionInterveneRef" :faapplyid="$route.params.faapplyid" :applyid="$route.params.applyid" :isMain="false" :isFlow="true"></CaseDecisionIntervene>
  </div>
</template>
<script>
import { setpFieldList } from '@/api/workflow/act_dsn_form_step.js'
import { St_field } from '@/enumeration/St_field.js'
import { viewByProcessStepId, viewLayoutByStepId } from '@/api/workflow/act_dsn_form_layout'
import { loadProcessForm } from '@/api/workflow/wf_ProcessInstance.js'
import { findStepRelation } from '@/api/workflow/act_dsn_form_step.js'
import { Tp_defaultvalue } from '@/enumeration/Tp_defaultvalue.js'
import storage from 'store'
import { APP_USER, APP_DEPT } from '@/store/mutation-types'
import { specialFieldList, Bus_FieldService, formControl } from '@/utils/formassembly/formfield.js'
import { ButtonClick } from '@/utils/formassembly/buttonconfig.js'

import '@/assets/css/form/theme.scss'
// 编辑模式下不能被更新的字段
// const FinalList = ['applycode', 'id', 'inittime']
const NO_FinalList = ['status', 'opinion']

export default {
  components: {
    buildBlocks: () => import('@/views/FormAssembly/formBuild.vue'),
    EditTargetName: () => import('@/views/accept/EditTargetName.vue'),
    ApprovalDocPreview: () => import('@/views/accept/ApprovalDocPreview.vue'),
    Comword: () => import('@/views/handleCase/base/component/Comword.vue'),
    CaseDecisionIntervene: () => import('@/views/handleCase/accept/CaseDecisionIntervene.vue')
  },
  props: {
    // 1 编辑模式, 2 预览模式 3 操作模式 4 详情模式 5 管理员模式
    pattern: {
      type: Number,
      default: 3,
    },
    // 渲染模式下显示的字段列表
    formid: {
      type: String,
      default: '',
    },
    applyid: {
      type: String,
      require,
    },
  },
  data() {
    return {
      currentUser: storage.get(APP_USER), // 登录人信息
      currentDept: storage.get(APP_DEPT), // 登录人部门
      nowStepid: null, // 当前环节的stepid
      isStart: false, // 是否处于发起流程
      fieldMap: {}, // 字段中间map
      loading: true, // 页面数据处理状态
      sonState: true, // 子表格校验的值
      defaultHidden: [], // 表单界面设计就设置为默认不显示的项
      childrenFormData: {}, // 子表格回显的数据 {表名: [列], ...}
      sonTableData: [], // 子表格输入的数据
      activeList: [], // 子表格显示的字段
      formKey: 0, // 表单重绘key
      St_field: St_field, // 字段状态类型枚举
      fieldList: [], // 字段配置列表
      stepMap: {}, // 字段控制显示对象 {步骤id, 对应步骤显示字段}
      EditMap: {}, // 编辑模式使用获取label
      activeItem: '', // 背景激活的项
      formData: {}, // 表单数据源
      queryParam: { pageSize: 2147483647, sort: 'indexsort', order: 'asc' }, // 回显查询条件
      formJson: { list: [], config: {} }, // formJson 表单源数据
      rules: {},
      theme: '',
    }
  },
  async created() {
    this.$nextTick(() => {
      this.theme = 'default'
      document.getElementById('taskForm').setAttribute('class', `theme_${this.theme}_task`)
      document.getElementById('tableForm').setAttribute('class', `theme_${this.theme}_form tableBox`)
    })
    // 获取json串
    // console.log('表单路由参数', this.$route.params)
    let formid = this.formid ? this.formid : this.$route.params.formid
    let res = await this.getFromJson(formid)

    // 加载动态枚举 (没刷新还在就不加载)
    // console.log('---', this.$store.state.form.formData.dynamicDataList)
    if (!this.$store.state.form.formData.dynamicDataList) {
      this.$store.dispatch('GetEnumValuesList')
    }

    if (res.code == 0) {
      // & 操作模式回显处理的逻辑
      this.formJson = JSON.parse(res.data.layout_) || {}
      // ^ 存储到Vux里面
      this.$store.commit('setLayoutData', this.formJson)

      // & 寻找永久隐藏的表单项
      this.findHidden(this.formJson || false)

      console.log('表单json', this.formJson)
      this.queryParam.f_formid_ = formid
      if (
        this.pattern == 3 &&
        this.$route.params.processinstanceid != undefined &&
        this.$route.params.taskid != undefined &&
        this.$route.params.stepid != undefined
      ) {
        // -上面流程相关的参数都有, 进入操作模式
        this.getSetpFieldList()
      } else if (this.pattern == 4) {
        await this.getFormData(formid, this.$route.params.processinstanceid)
      } else {
        this.queryParam.f_formid_ = formid
        this.getSetpFieldList()
      }

      // ^ 保存表单数据到Vuex
      console.log('表单数据', this.formData)
      this.$store.commit('setPrecessform', this.formData)
    }

    // console.log('表单绑定数据', this.formData)
    // console.log('父组件编辑数据', this.EditMap)
    // console.log('表单校验', this.rules)

    // - 获取环节配置数据
    // console.log('stepMap', this.stepMap)
  },
  methods: {
    // 回显切换回来vuex意见存储的表单字段记录
    echoVuex() {
      console.log('echoVuex', this.$store.state.Processform.formData)
    },
    changestyle() {
      if (this.theme == 'default') {
        this.theme = 'approve'
      } else {
        this.theme = 'default'
      }
      this.$nextTick(() => {
        document.getElementById('taskForm').setAttribute('class', `theme_${this.theme}_task`)
        document.getElementById('tableForm').setAttribute('class', `theme_${this.theme}_form tableBox`)
      })
    },
    // 按钮组件的点击事件
    s_btnClick(value) {
      console.log('子按钮组件点击', value)
      // 自定义按钮点击业务逻辑
      ButtonClick(value, this)
    },
    // 给子组件触发单个字段的重新校验
    s_updateCheck(field) {
      // console.log('单个校验', field, this.formData[field])
      // this.$refs.refForm_1.validateField(field)
      this.$refs.refForm_1.clearValidate(field)
    },
    // 查找永久隐藏的字段
    findHidden(formJson) {
      if (formJson && formJson.list) {
        this.formJson.list.forEach((v) => {
          // & 存储默认就要隐藏的字段
          this.hiddenItem(v)
        })
      }
      // console.log('永久隐藏', this.defaultHidden)
    },
    // 隐藏的项
    hiddenItem(v) {
      if (v.columns) {
        v.columns.forEach((obj) => {
          this.hiddenItem(obj)
        })
      } else if (v.list) {
        v.list.forEach((b) => {
          this.hiddenItem(b)
        })
      } else if (v.trs) {
        // ^ 表格类型的处理逻辑
        v.trs.forEach((tr) => {
          this.hiddenItem(tr)
        })
      } else if (v.tds) {
        // ^ 表格类型的处理逻辑
        v.tds.forEach((td) => {
          this.hiddenItem(td)
        })
      } else {
        if (v.options.hidden == true || v.options.hidden == 'true') {
          this.defaultHidden.push(v.pk)
        }
      }
    },
    // & 编辑模式下需要知道环节列表
    async findStepRelation(formid) {
      let nodeList = []
      let index = -1
      let beforeIds = [] // 之前环节数组
      let afterIds = [] // 之后环节数组
      let res = await findStepRelation(formid, 3, this.$route.params.processdefinitionid).then((res) => {
        return res
      })
      console.log('环节列表-son', res)
      if (res.code == 0) {
        nodeList = res.data || []
        if (nodeList.length == 0) {
          this.loading = false
          this.$message.error('流程未配置环节')
          return
        }
        index = -1
        if (this.$route.params.stepid != undefined) {
          nodeList.forEach((v, i) => {
            if (v.stepid_ == this.$route.params.stepid) {
              index = i
            }
          })
        } else {
          // 没有就是处于发起环节
          this.isStart = true
          index = 0
        }

        // 找到当前自己所处的环节, 没找到return
        // console.log('index', index)
        // & 本来是父组件调用的, 编辑模式下没有, 字段动手丰衣足食,
        // 找出之前, 之后环节的id

        for (let i = index - 1; i >= 0; i--) {
          beforeIds.push(nodeList[i].id)
        }
        for (let i = index + 1; i <= nodeList.length - 1; i++) {
          afterIds.push(nodeList[i].id)
        }
      }

      if (index == -1) {
        this.$message.warning('未找到当前环节')
        return
      }
      this.nowStepid = nodeList[index].id
      // console.log('当前环节', this.nowStepid)
      // 开始节点不回显表单数据接口
      if (this.isStart == false) {
        // 找到按钮回显环节需要用到的id
        this.$nextTick(() => {
          if (this.$route.params.taskid != 'undefined' && this.$route.params.taskid != undefined) {
            console.log('流程环节按钮配置列表', nodeList)
            this.$emit('f_getStepBtnList', nodeList[index].id)
            // 按钮抽离 this.$refs.btnRef.getStepBtnList(nodeList[index].id)
          }
        })
        await this.getFormData(formid, this.$route.params.processinstanceid)
      } else {
        this.fromInit(this.formJson || false)
      }
      this.nowStepid = nodeList[index].id
      this.fGender(nodeList[index].id, beforeIds, afterIds)
    },
    //获取流程关联表单数据
    async getFormData(formid, processinstanceid) {
      // 等于4表示查询已完成的表单数据
      let state = this.pattern != 4 ? 1 : 2
      await loadProcessForm(formid, processinstanceid, state).then((res) => {
        console.log('回显表单数据', res)
        if (res.code == 0) {
          for (let key in res.data) {
            // 主表是对象, 其它主表和从表示数组
            if (key == 'master') {
              let model = res.data[key].model
              for (let modelKey in model) {
                if (NO_FinalList.includes(modelKey)) {
                  continue
                }
                const s_key = res.data[key].table + '#' + modelKey
                this.$set(this.formData, s_key, model[modelKey])
              }
            } else if (['extend', 'lookup'].includes(key)) {
              // 其它类型主表
              res.data[key].forEach((v) => {
                for (let modelKey in v.model) {
                  if (NO_FinalList.includes(modelKey)) {
                    continue
                  }
                  const s_key = v.table + '#' + modelKey

                  this.$set(this.formData, s_key, v.model[modelKey])
                }
              })
            } else if (key == 'slave') {
              // console.log('从表', key)
              // 子表格对象组装
              let tableList = res.data[key]
              tableList.forEach((v) => {
                let tempArr = []
                v.model.forEach((m) => {
                  let obj = {}
                  for (let mKey in m) {
                    if (NO_FinalList.includes(mKey)) {
                      continue
                    }
                    obj[v.table + '#' + mKey] = m[mKey]
                  }
                  tempArr.push(obj)
                  // this.childrenFormData[v.table] = tempArr
                })
                this.childrenFormData[v.table] = tempArr
              })
            }
          }
        }
        // console.log('子表格回显数据', this.formData, this.childrenFormData)
        this.fromInit(this.formJson || false)
        // 组装好数据再初始化
      })
    },
    // 获取表单布局json
    async getFromJson(formid) {
      // 配置模式下 stepid是表单配置环节id, 操作模式下是流程环节的stepid
      let res
      if (this.pattern == 1) {
        res = await viewLayoutByStepId({ formid: formid, stepid: this.$route.params.stepid })
      } else {
        res = await viewByProcessStepId({ formid: formid, stepid: this.$route.params.stepid })
      }
      return res
    },
    // 给父组件调用, 控制表单显示状态
    fGender(stepid, beforeIds, afterIds) {
      // console.log('***', stepid, this.stepMap[stepid], this.stepMap)
      console.log('当前环节', stepid)
      this.nowStepid = stepid
      let currentArr = this.stepMap[stepid] || [] // 当前环节数组
      let beforeArr = [] // 之前环节数组
      beforeIds.forEach((id) => {
        if (id in this.stepMap) {
          beforeArr = beforeArr.concat(this.stepMap[id])
        }
      })
      // - 子表单需要显示的字段
      if (
        this.pattern == 3 &&
        this.isStart == false &&
        (this.$route.params.taskid == 'undefined' || this.$route.params.taskid == undefined)
      ) {
        this.activeList = []
      } else {
        this.activeList = currentArr
      }

      // console.log('子表格可编辑的项*', this.$route.params.taskid, this.activeList, this.stepMap, stepid)

      let afterArr = [] // 之后环节数组
      afterIds.forEach((id) => {
        if (id in this.stepMap) {
          afterArr = afterArr.concat(this.stepMap[id])
        }
      })
      // console.log(stepid, '现在', currentArr, '之前', beforeArr, '之后', afterArr)
      // 4. 找出当前环节的配置信息转map
      let fieldMap = {}
      this.fieldList.forEach((v) => {
        if (currentArr.includes(v.field_) && stepid == v.stepid_) {
          fieldMap[v.field_] = v
        }
      })
      // 1. 把当前环节根据配置显示
      // 2. 把之前环节, 默认值显示
      // 3. 把之后环节, 隐藏
      this.formJson.list.forEach((v) => {
        this.fieldProcessing(fieldMap, currentArr, beforeArr, afterArr, v)
      })

      setTimeout(() => {
        this.$nextTick(() => {
          this.loading = false
        })
      }, 500)
    },
    // 控件状态, 回显递归处理函数
    fieldProcessing(fieldMap, currentArr, beforeArr, afterArr, v) {
      if (v.columns) {
        v.columns.forEach((obj) => {
          this.fieldProcessing(fieldMap, currentArr, beforeArr, afterArr, obj)
        })
      } else if (v.list) {
        v.list.forEach((b) => {
          this.fieldProcessing(fieldMap, currentArr, beforeArr, afterArr, b)
        })
      } else if (v.trs) {
        // ^ 表格类型的处理逻辑
        v.trs.forEach((tr) => {
          this.fieldProcessing(fieldMap, currentArr, beforeArr, afterArr, tr)
        })
      } else if (v.tds) {
        // ^ 表格类型的处理逻辑
        v.tds.forEach((td) => {
          this.fieldProcessing(fieldMap, currentArr, beforeArr, afterArr, td)
        })
      } else {
        // 直接配置
        if (currentArr.includes(v.pk) && v.pk in fieldMap) {
          let config = fieldMap[v.pk]
          // 如果有 "自动赋值" 则回显 (系统默认值)
          if (config.value_) {
            // 系统默认值
            const variable = config.value_.replace(/(^\s*)|(\s*$)/g, '')

            if (variable in Tp_defaultvalue) {
              setTimeout(() => {
                this.updatedValueS(v.pk, this.getSystemValue(variable))
              }, 1000)
              // console.log('返回值',this.formData[v.pk])
            } else {
              this.updatedValueS(v.pk, variable)
            }
          }

          if (config.status_ == this.St_field[90600].value) {
            v.options.disabled = false
            v.options.hidden = false
          } else if (config.status_ == this.St_field[90601].value) {
            v.options.hidden = true
          }
        } else if (beforeArr.includes(v.pk) || afterArr.includes(v.pk)) {
          v.options.hidden = false
          v.options.disabled = true
        } else {
          v.options.disabled = true
        }
        // & 处于默认隐藏状态的字段权限最大, 一直隐藏
        // console.log('一直隐藏', this.defaultHidden)
        if (this.defaultHidden.includes(v.pk)) {
          v.options.hidden = true
        }
        v.options.pattern = this.pattern
        // 把字段配置信息存入map, 后续用不用递归
        if (v.pk) {
          formControl[v.pk] = v
        }
      }
    },
    // 环节配置信息
    getSetpFieldList() {
      setpFieldList(this.queryParam)
        .then((res) => {
          console.log('环节配置信息', res)
          if (res.code == 0) {
            this.fieldList = res.data.records || []
            res.data.records.forEach((v) => {
              this.fieldMap[v.field_] = v
              if (v.stepid_ in this.stepMap) {
                this.stepMap[v.stepid_].push(v.field_)
              } else {
                this.stepMap[v.stepid_] = [v.field_]
              }
            })
            // console.log('环节配置信息**', res, this.stepMap, this.nowStepid)
          }
          if (this.pattern == 3 || this.pattern == 5) {
            // & 编辑模式下手动触发控制控件显示状态
            this.findStepRelation(this.$route.params.formid)
          } else {
            this.fromInit(this.formJson || false)
            // 非编辑模式, 默认回显父组件第一个
            this.$emit('fGender', 0)
            this.formKey++
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },
    // 编辑模式下父组件给数据
    fSetActive(id) {
      console.log('焦点', id)
      if (this.pattern == 1) {
        this.activeItem = id
      }
    },
    // 字段绑定模式下, 鼠标移入
    rowMouseOver(item) {
      if (this.pattern == 1) {
        this.activeItem = item.pk
        this.$emit('fSetActive', true, item)
      }
    },
    // 字段绑定模式下, 鼠标移出
    resMouseleave(item) {
      if (this.pattern == 1) {
        this.activeItem = ''
        this.$emit('fSetActive', false, item)
      }
    },
    // 字段绑定模式下, 双击添加
    rowDbclick(item) {
      if (this.pattern == 1) {
        // console.log('子添加', item)
        this.$emit('fAddItem', true, item)
      }
    },
    // 代替子函数触发事件
    sTriggerEvent(functionString) {
      // 代理字符串的this到我们备份到this的对象上
      functionString = functionString.replace(/this\[/g, 'this.formData[')
      eval(functionString)
      console.log('代替触发', functionString)
    },
    // 子组件给父组件保存数据
    sSetFormData(data) {
      // console.log('子表格的数据', data)
      this.sonTableData.push(data)
    },
    // 子表格校验赋值方法
    sSetSonState(check) {
      // console.log('子表格校验111', check)
      if (this.sonState == false) {
        return
      }
      this.sonState = check
    },
    // 通过方法
    saveForm(isSon = false) {
      // 手动校验文件类型表单项
      let state = true
      console.log('校验', this.formData)
      let checkObj = null
      this.$refs.refForm_1.validate((valid, errCheck) => {
        console.log('valid', valid)
        if (!valid) {
          if (errCheck) {
            for (let key in errCheck) {
              checkObj = errCheck[key][0] ? errCheck[key][0] : null
              break
            }
          }
          console.log('失败2')
          state = false
        }
      })
      // - 要清空子表格数据
      this.sonTableData = []
      // 子表单校验(不一定只有一个), 循环校验
      this.sonState = true
      this.$refs.formBuildRef.forEach((v) => {
        // 嵌套组件继续校验
        if (v.$refs.nestedComponents != undefined) {
          v.$refs.nestedComponents.forEach((j) => {
            j.buildCheck(j)
          })
        } else {
          v.buildCheck(v)
        }
      })
      // console.log('子表格校验222', this.sonState)
      if (this.sonState == false) {
        this.$message.warning('请填写表单必填项')
      }
      // 所有校验都通过, 开始保存表单
      if (state) {
        // console.log('开始保存', this.formData)
        // 组装保存数据
        let body = this.getSaveBody()
        // console.log('body', body)
        // & 判断是子组件调用还是父组件调用
        if (isSon) {
          this.$emit('f_SetFormData', body)
          // 按钮抽离 this.$refs.btnRef.sSetFormData(body)
        } else {
          this.$emit('fSetFormSave', body, this.formData[this.formJson.config.mainField] || '')
        }
      } else {
        // 如果有自定义校验规则, 用自定义校验规则的提示
        if (checkObj != null && checkObj.message != '必填项') {
          this.$message.warning(checkObj.message)
        } else {
          this.$message.warning('请填写表单必填项')
        }
      }
    },
    // 组装保存数据 - formData Map<表名, list<Map<"field: 字段, value: 值", "variable: 变量名">>>
    getSaveBody() {
      // 1 获取节点列表, 找出环节配置的流程变量
      // console.log('子表格', this.sonTableData)
      let variableMap = {}
      this.fieldList.forEach((v) => {
        if (v.variname_ != null) {
          // console.log('v', v, v.variname_, v.variname_ != '')
          variableMap[v.field_] = v.variname_
        }
      })
      console.log('variableMap', variableMap)
      // 2 组装数据
      let body = {}
      if (JSON.stringify(this.formData) != '{}') {
        for (let key in this.formData) {
          // console.log('key', key, this.formData[key])
          // 值为null的字段不操作
          if (key.indexOf('#') == -1 || [null].includes(this.formData[key])) {
            // console.log('key2', key, this.formData[key])
            continue
          }
          let obj = {
            field: key.substring(key.indexOf('#') + 1, key.length),
            value: this.formData[key],
          }
          // 绑了流程变量多配置一个属性
          if (key in variableMap) {
            obj.variable = variableMap[key]
          }

          if (key.substring(0, key.indexOf('#')) in body == false) {
            body[key.substring(0, key.indexOf('#'))] = [obj]
          } else {
            // console.log('body-obj', obj)
            body[key.substring(0, key.indexOf('#'))].push(obj)
          }
        }
      }
      // 配置从表的数据(子表格) 和主表不一样, 是数组形式
      // tablename: {0: [{}], 1: [{}]}
      if (this.sonTableData.length > 0) {
        this.sonTableData.forEach((item) => {
          if (JSON.stringify(item) != '{}') {
            let model = {}
            let tableName = ''
            for (let key in item) {
              let num = key.match(/\d+/g)
              // console.log('num', num, key)
              // console.log('第几个', key, key.match(/\d+/g))
              // console.log('num', num)
              if (num == null || num.length == 0 || null == item[key]) {
                continue
              }
              if (tableName == '') {
                tableName = key.substring(0, key.indexOf('#'))
              }
              let obj = {
                field: key.substring(key.indexOf('#') + 1, key.indexOf(String(num[0]))),
                value: item[key],
              }
              if (String(num[0]) in model == false) {
                model[String(num[0])] = [obj]
              } else {
                model[String(num[0])].push(obj)
              }
            }
            if (tableName != '') {
              body[tableName] = model
            }
          }
        })
      }
      return body
    },
    // 获取系统配置表达式的默认值
    getSystemValue(value) {
      // console.log('***', value)
      // console.log('用户', this.currentUser, this.currentUser.sectionid)
      //console.log('部门', this.currentDept)
      switch (value) {
        case 'user.fullname':
          return this.currentUser.fullname
        case 'user.id':
          return this.currentUser.userId
        case 'user.username':
          return this.currentUser.username
        case 'dept.id':
          return this.currentDept.id
        case 'dept.name':
          return this.currentDept.name
        case 'dept.sectionid':
          return this.currentDept.sectionid
        case 'dept.sectionname':
          return this.currentDept.sectionname
        case 'dept.adid':
          return this.currentUser.adid
        case 'now.date':
          return this.$moment().format('YYYY-MM-DD HH:mm:ss')
        case 'now.datetime':
          return this.$moment().format()
        case 'now.time':
          return this.$moment().format('HH:mm:ss')
        default:
          this.$message.error('未知的表达式' + value)
      }
    },
    // 子组件更新父组件数据
    updatedValueS(id, value, test) {
      console.log('更新值', id, value, test, this.formData)
      
      // 监听赋值需要特殊处理的key
      if (specialFieldList.includes(id)) {
        Bus_FieldService(this.$route.params.applyid, id, value, this, this.$store.state)
      } else {
        this.$set(this.formData, id, value)
      }
    },
    // 表格初始化
    fromInit(formJson) {
      console.log('初始化')
      // console.log('初始化方法', )
      // 执行全局初始化函数
      if (formJson.initFunc) {
        eval(formJson.initFunc)
      }
      // 配置渲染操作
      if (formJson && formJson.list) {
        this.formJson.list.forEach((v) => {
          // console.log('v---', v.type, v)
          // & 初始化, 栅格嵌套组件处理方式
          this.handleItem(v)
        })
      }

      if (this.pattern == 1 || this.pattern == 4 || this.pattern == 5) {
        this.loading = false
      }

      // 编辑模式下给数据
      // console.log('模式', this.pattern,this.EditMap)
      if (this.pattern == 1) {
        this.$emit('fGetEditData', this.EditMap)
      }

      // console.log('表单规则', this.rules)
    },
    // 递归渲染栅格类型, 并根据嵌套层级配置对应的span
    handleItem(v) {
      // console.log('son', son)
      if (v.columns) {
        v.columns.forEach((obj) => {
          this.handleItem(obj)
        })
      } else if (v.list) {
        v.list.forEach((b) => {
          this.handleItem(b)
        })
      } else if (v.trs) {
        // ^ 表格类型的处理逻辑
        // console.log('tr+++', v)
        v.trs.forEach((tr) => {
          this.handleItem(tr)
        })
      } else if (v.tds) {
        // ^ 表格类型的处理逻辑
        v.tds.forEach((td) => {
          this.handleItem(td)
        })
      } else {
        if (
          v.type == 'text' &&
          this.nowStepid != null &&
          this.nowStepid in this.stepMap &&
          this.stepMap[this.nowStepid].includes(v.key)
        ) {
          // 如果当前环节配了文本节点, 那就让它隐藏
          v.options.hidden = true
          return
        } else if (v.pk == undefined) {
          return
        }
        // 配置校验规则
        if (v.rules) {
          this.addRule(v)
        }
        // - 控制显示状态
        v.options.pattern = this.pattern
        if (this.pattern == 1 || this.pattern == 4 || this.pattern == 5) {
          v.options.disabled = true
        }

        this.EditMap[v.pk] = v
        // 编辑模式下, 存子表格的键值
        // console.log('pattern', this.pattern)
        if (this.pattern == 1) {
          // 动态表格继续找里面的值
          if (v.type == 'batch') {
            v.list.forEach((b) => {
              this.EditMap[b.pk] = b
            })
          }
        } else if (this.pattern == 2) {
          // - 渲染模式下给环节预览描述
          v.options.explain = this.getDefaultValue(v.type)
        }
        // 将v-model数据置空
        if (v.pk && v.pk in this.formData && this.formData[v.pk] != 'null') {
          // 有默认值回显默认值
          this.$set(this.formData, v.pk, this.formData[v.pk])
        } else if (v.pk && v.options && v.options.defaultValue) {
          if (v.options.defaultValue instanceof Array) {
            this.$set(this.formData, v.pk, v.options.defaultValue.join(','))
          } else {
            // & json可能为空数组串
            if (v.options.defaultValue == '[]') {
              this.$set(this.formData, v.pk, [])
            } else {
              this.$set(this.formData, v.pk, v.options.defaultValue)
            }
          }
        } else if (v.pk) {
          this.$set(this.formData, v.pk, null)
        }
      }
    },
    // 控件类型描述
    getDefaultValue(type) {
      switch (type) {
        case 'text': {
          return '表单标题'
        }
        case 'input': {
          return '文本输入框'
        }
        case 'radio': {
          return '单选框'
        }
        case 'number': {
          return '数字输入框'
        }
        case 'checkbox': {
          return '多选框'
        }
        case 'textarea': {
          return '文本域'
        }
        case 'numradiober': {
          return '单选框'
        }
        case 'select': {
          return '下拉选择器'
        }
        case 'date': {
          return '日期选择器'
        }
        case 'uploadImg': {
          return '图片上传'
        }
        case 'uploadFile': {
          return '文件上传'
        }
        case 'treeSelect': {
          return '树形选择器'
        }
        case 'cascader': {
          return '级联选择器'
        }
        case 'time': {
          return '时间选择器'
        }
        default: {
          return '表单控件'
        }
      }
    },
    // 配置校验规则
    addRule(value) {
      if (value.type == 'text') {
        return
      } else {
        let tempruleList = []
        value.rules.forEach((v) => {
          if (value.type == 'select' && value.options.multiple) {
            v.trigger = 'array'
          } else {
            v.trigger = 'change'
          }
          tempruleList.push(v)
        })
        this.rules[value.pk] = tempruleList
      }
    }
  },
}
</script>

<style lang="scss" scoped>
// 子组件拷贝文本颜色
// /deep/ .copy_text:hover {
//   color: #2972fa;
//   cursor: pointer;
//   background-color: rgb(201, 237, 252);
// }
// /deep/ .formMaringBox beyond_hiding {
//   min-height: 40px;
//   // border: 1px solid red;
// }

// // 容器超出显示... xiaohao
// /deep/ .beyond_hiding {
//   width: 100%;
//   overflow: hidden;
//   white-space: nowrap;
//   text-overflow: ellipsis;
// }

// /deep/ .ant-form-item-label {
//   // 统一布局样式 ?
//   // min-width: 100px !important;
//   // border: 1px solid red;
//   font-weight: 550;
// }

// /deep/ .ant-form-item-label {
//   // 统一布局样式 ?
//   // width: 100px !important;
// }
// /deep/ .ant-row {
//   position: relative;
//   height: auto;
//   margin-right: 0;
//   margin-left: 0;
//   zoom: 1;
//   hidden: block;
//   -webkit-box-sizing: border-box;
//   box-sizing: border-box;
// }
// /deep/ .tableTitleBox {
//   text-align: center;
//   font-weight: 600;
//   font-size: 20px;
//   font-family: SimHei;
//   padding: 10px 0;
// }

// .tableBox {
//   width: 94%;
//   margin: 0 auto;
//   padding-bottom: 50px;
//   padding-top: 30px;
//   // border: 1px solid blue;
// }
// .templateBox {
//   // border: 1px solid blue;
//   background-color: #fff;
// }
.tableBox {
  ::v-deep .ant-btn {
    color: #0072c6;
    background: #f2f8fc;
    border: 1px solid #f2f8fc;
    border-radius: 5px;
  }
}
</style>
